<template>
  <a-modal
    v-model="visible"
    :title="ws ? '完善企业信息' : mType ? '新建招工企业' : '编辑招工企业'"
    @ok="handleOk"
    @cancel="$emit('update:visible', false)"
  >
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" :colon="false">
      <a-form-item label="企业logo" style="height: 84px; position: relative">
        <a-upload
          accept=".jpg, .jpeg, .png"
          list-type="picture-card"
          action="/file/api/v1/general/uploadImg"
          name="files"
          :file-list="fileList"
          :beforeUpload="beforeUpload"
          @preview="handlePreview"
          @change="handleUpChange"
          class="uploads"
        >
          <div v-if="fileList.length === 0">
            <a-icon type="plus" />
            <!-- <div class="ant-upload-text">
              上传
            </div> -->
          </div>
        </a-upload>
        <div class="uploadFont">
          <div>点击上传logo</div>
          <div>支持png, jpg, 大小不超过1m</div>
        </div>
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
        <a-input v-show="false" v-decorator="['logos', { rules: [{ required: true, message: '企业logo不能为空' }] }]" />
      </a-form-item>
      <a-form-item label="企业全称">
        <a-input
          placeholder="请输入"
          :maxLength="50"
          v-decorator="['name', { rules: [{ required: true, message: '企业全称不能为空' }] }]"
        />
      </a-form-item>
      <a-form-item label="联系人姓名">
        <a-input
          :maxLength="50"
          v-decorator="['legalPerson', { rules: [{ required: true, message: '联系人姓名不能为空' }] }]"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="联系电话">
        <a-input v-decorator="['companyTelephone', { rules: [{ required: true, message: '联系电话不能为空' }] }]" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="联系邮箱">
        <a-input
          placeholder="请输入"
          v-decorator="[
            'companyEmail',
            {
              rules: [
                {
                  type: 'email',
                  message: '请输入正确邮箱'
                }
              ]
            }
          ]"
        />
      </a-form-item>
      <a-form-item label="企业地址">
        <city :default-value="socCity" :level="2" @change="handleCity($event)" />
        <a-input v-show="false" v-decorator="['socCity', { rules: [{ required: true, message: '地区不能为空' }] }]" />
      </a-form-item>
      <a-form-item label=" " class="dnone">
        <!-- <city
            :default-value="socCity"
            :level="2"
            @change="handleCity($event)"
            style="margin-bottom: 28px;"
          /> -->
        <a-input placeholder="请输入详细地址" v-decorator="['address', { rules: [{ required: true, message: '详细地址不能为空' }] }]" />
      </a-form-item>
      <a-form-item label="企业性质">
        <a-select v-decorator="['properties']" placeholder="请选择">
          <a-select-option :value="item" v-for="item in propertiesArr" :key="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="企业行业">
        <a-select v-decorator="['companyIndustryFirst']" placeholder="请选择">
          <a-select-option :value="item" v-for="item in companyIndustryFirstArr" :key="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="企业规模">
        <a-select v-decorator="['personSize']" placeholder="请选择">
          <a-select-option :value="item.id" v-for="item in personSizeArr" :key="item.id">
            {{ item.v }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { postCompanyUnits, putCompanyUnits } from "../api";
import { AreaPicker as city } from "xqjr-plugin-common";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

const propertiesArr = [
  "国企",
  "民营",
  "合资",
  "外企独资",
  "股份制企业",
  "上市企业",
  "代表处",
  "国家机关",
  "事业单位",
  "银行",
  "医院",
  "学校/夏季学院",
  "律师事务所",
  "社会团体",
  "港澳台企业",
  "其他"
];

const companyIndustryFirstArr = [
  "互联网/IT/电子/通信",
  "能源/环保/矿产",
  "教育培训/科研",
  "卫生及社会工作",
  "公共管理/社会保障",
  "生活服务",
  "农林牧渔",
  "房地产",
  "金融业",
  "交通运输/仓储/物流",
  "制造业",
  "建筑业",
  "批发/零售/贸易",
  "专业服务",
  "文化/体育/娱乐"
];

const personSizeArr = [
  { id: 1, v: "0-20" },
  { id: 2, v: "20-99" },
  { id: 3, v: "99-200" },
  { id: 4, v: "200-500" },
  { id: 5, v: "500-1000" },
  { id: 6, v: "1000以上" }
];

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    mType: {
      type: Boolean,
      default: true
    },
    ws: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ""
    },
    dataJson: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    city
  },
  watch: {
    visible(v) {
      if (v) {
        this.fileList = [];
        this.logo = "";
        this.socCity = "";
        this.socCityName = "";
        this.form.resetFields();
        if (!this.mType) {
          if (this.dataJson?.logo) {
            this.logo = this.dataJson.logo;
            this.fileList = [
              {
                uid: "-1",
                name: "image.png",
                status: "done",
                url: this.dataJson.logo
              }
            ];
          }
          this.socCity = this.dataJson.socCity;
          this.socCityName = this.dataJson.socCityName;
          setTimeout(() => {
            this.form.setFieldsValue({
              name: this.dataJson.name,
              legalPerson: this.dataJson.legalPerson,
              companyTelephone: this.dataJson.companyTelephone,
              companyEmail: this.dataJson.companyEmail,
              address: this.dataJson.address,
              properties: this.dataJson.properties,
              companyIndustryFirst: this.dataJson.companyIndustryFirst,
              personSize: this.dataJson.personSize,
              officialWebsite: this.dataJson.officialWebsite,
              profile: this.dataJson.profile,
              socCity: this.dataJson.socCity,
              logos: this.dataJson.logo
            });
          }, 100);
        }
      }
    }
  },
  data() {
    return {
      previewImage: "",
      previewVisible: false,
      logo: "",
      fileList: [],
      form: this.$form.createForm(this, {}),
      socCity: "",
      socCityName: "",
      propertiesArr,
      companyIndustryFirstArr,
      personSizeArr
    };
  },
  methods: {
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.address = [this.socCity, this.socCityName, values.address].join(",");
          values.logo = this.logo;
          delete values.logos;
          this.mType ? this.onPostCompanyUnits(values) : this.onPutCompanyUnits(values);
        }
      });
    },
    async onPostCompanyUnits(v) {
      try {
        await postCompanyUnits(v);
        this.$emit("upDate");
        this.$emit("update:visible", false);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    async onPutCompanyUnits(v) {
      try {
        v.id = this.id;
        await putCompanyUnits(v);
        this.$emit("upDate");
        this.$emit("update:visible", false);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    handleCity(e) {
      if (e.value.length > 0) {
        const value = e.value;
        const label = e.label;
        this.socCity = value[value.length - 1].toString();
        if (label.length && label.length === 3) {
          this.socCityName = label[0] + "/" + label[1] + "/" + label[2];
        } else if (label.length && label.length === 2) {
          this.socCityName = label[0] + "/" + label[1];
        } else if (label.length && label.length === 1) {
          this.socCityName = label[0];
        }
      } else {
        this.socCity = "";
        this.socCityName = "";
      }
      setTimeout(() => {
        this.form.setFieldsValue({
          socCity: this.socCity
        });
      }, 100);
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleUpChange(e) {
      this.fileList = e.fileList;
      if (e.fileList.length === 0) {
        this.fileList = [];
      }
      if (!e.file?.status) {
        this.fileList = [];
      }
      const logo = [];
      e.fileList.forEach((item, index) => {
        if (item.status === "done") {
          if (item.response.data && item.response.data[0]) {
            logo.push(item.response.data[0]);
          } else {
            this.$message.error("上传图片失败");
          }
        }
      });
      if (logo.length > 0) {
        this.logo = logo.join(",");
        setTimeout(() => {
          this.form.setFieldsValue({
            logos: logo.join(",")
          });
        });
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$message.error("图片上传大小不能超过 1MB!");
      }
      return isLt2M;
    }
  }
};
</script>

<style lang="scss" scoped>
.dnone {
  ::v-deep .ant-form-item-required::before {
    display: none;
  }
}
.uploads {
  ::v-deep.ant-upload-select-picture-card {
    width: 80px;
    height: 80px;
  }
  ::v-deep.ant-upload-list-picture-card-container {
    width: 80px;
    height: 80px;
  }
  ::v-deep.ant-upload-list-item-list-type-picture-card {
    width: 80px;
    height: 80px;
  }
}
.uploadFont {
  position: absolute;
  top: -44px;
  left: 90px;
  font-size: 12px;
  color: #a6a8b4;
  text-align: left;
  div {
    height: 20px;
  }
}
</style>
